package com.jyw.business.de.expand.task;

import cn.hutool.core.util.StrUtil;
import com.jyw.business.de.constant.DemandStateConstant;
import com.jyw.business.de.domain.DeDemandAllocation;
import com.jyw.business.de.domain.DeDemandInfo;
import com.jyw.business.de.service.IDeDemandAllocationService;
import com.jyw.business.de.service.IDeDemandInfoService;
import com.jyw.business.de.service.ISysDemandReminderConfigService;
import com.jyw.business.obstacles.service.IObsOrderMessageService;
import com.jyw.common.constant.CacheConstants;
import com.jyw.common.core.redis.RedisCache;
import com.jyw.common.utils.DateUtils;
import com.jyw.system.domain.vo.SysDemandReminderConfigVo;
import com.jyw.system.enums.MessageTypeEnum;
import com.jyw.system.service.ISysMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 需求超时未接收提醒
 */
@Component("DeDemandAcceptTask")
@Slf4j
public class DeDemandAcceptTask {

    @Resource
    private IDeDemandInfoService deDemandInfoService;

    @Resource
    private ISysDemandReminderConfigService configService;

    @Resource
    private IDeDemandAllocationService allocationService;

    @Resource
    private ISysMessageService messageService;

    @Resource
    private RedisCache redisCache;

    public void remind(){
        SysDemandReminderConfigVo config = configService.getDefaultConfig();
        //超时未分配开关
        if (config.getDemandAcceptTimeoutRemind()) {
            Date timeOut = DateUtils.addMinutes(DateUtils.getNowDate(), -config.getDemandAcceptTimeoutMinute());
            List<DeDemandInfo> list = deDemandInfoService.lambdaQuery()
                    .eq(DeDemandInfo::getDemandState, DemandStateConstant.ACCEPT)
                    .le(DeDemandInfo::getWaitAcceptTime, timeOut)
                    .list();
            list.forEach(data->{
                //查询需求分配人员
                List<DeDemandAllocation> allocationList = allocationService
                        .lambdaQuery()
                        .eq(DeDemandAllocation::getDemandId, data.getId()).list();
                if(!redisCache.hasKey(CacheConstants.DE_DEMAND_WAIT_ACCEPT_KEY+data.getId())){
                    messageService.sendBatchSysMessage(MessageTypeEnum.SYS_DEMAND.getValue(),
                            allocationList.stream().map(DeDemandAllocation::getAllocationUser).collect(Collectors.toList()),
                            StrUtil.format("需求【{}】,超时未接收,请尽快处理",data.getDemandTitle()));
                    redisCache.setCacheObject(CacheConstants.DE_DEMAND_WAIT_ACCEPT_KEY+data.getId(),data,config.getDemandAcceptTimeoutInterval(),TimeUnit.MINUTES);
                }
            });
        }
    }
}
